package com.zhoujing.rabbltmq.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 周敬
 * @version 1.0
 * @createTime 2022/7/1-16:23-星期五
 *
 * 消费者接收消息
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("kaibox.top");
        factory.setPort(5672);
        factory.setHandshakeTimeout(60000);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明 接收消息
        DeliverCallback deliverCallback = (consumerTag,message)->{
            // 消息分为很多，如：消息头，消息体，……，我们只需要获取消息体
            System.out.println(new String(message.getBody()));
        };

        // 取消消息时的回调
        CancelCallback cancelCallback = consumerTag->{
            System.out.println("消息消费被中断");
        };

        /*
        * 消费者消费消息
        * 1、消费哪个队列
        * 2、消费成功之后是否自动应答，true代表的自动应答，false代表手动应答
        * 3、当消息传达后回调
        * 4、消费者取消消费的回调
        * */
        channel.basicConsume(Producer.QUEUE_NAME,true,deliverCallback,cancelCallback);
    }
}
